<template>
  <div class="shop">
    <div class="top">
      <div class="topflex">
        <el-button
          @click="HandMovement"
          class="close"
          type="info"
          plain
          v-bind:disabled="isButtonDisabled"
          >手动输入二维码</el-button
        >
      </div>
    </div>
    <div class="middle" v-if="shopdata.length">
      <div class="myrowshow">
        <el-row v-for="(item, index) in shopdata" :key="index" class="shopimg">
          <el-card>
            <div style="line-height: 5rem">
              {{ index + 1 }}
            </div>
            <div>
              <img
                :src="dataimg"
                class="image"
                style="width: 5rem; height: 5rem"
              />
            </div>
            <div style="font-size: 20px; line-height: 5rem">
              {{ item.name }}
            </div>
            <div style="line-height: 5rem">
              <el-input-number
                v-model="item.num"
                :min="1"
                :max="100"
                label="数量"
                size="mini"
                ref="suminput"
              ></el-input-number>
            </div>
            <div>
              <i
                style="font-size: 70px"
                class="el-icon-circle-close"
                @click="del(item, index)"
              ></i>
            </div>
          </el-card>
        </el-row>
      </div>
    </div>
    <el-empty :image-size="700" v-else></el-empty>
    <div class="bottom">
      <div class="buttomflex">
        <el-button
          @click="Outbound"
          class="close"
          type="primary"
          v-bind:disabled="isButtonDisabled"
          >出库</el-button
        >
        <el-button
          @click="goblack"
          class="close"
          type="danger"
          v-bind:disabled="isButtonDisabled"
          >取消出库</el-button
        >
      </div>
    </div>

    <!-- 手动输入dialog -->
    <el-dialog
      :visible.sync="isshow"
      :close-on-click-modal="false"
      width="80%"
      :show-close="false"
    >
      <template slot="title">
        <div class="custom-title">
          手动输入二维码
          <i class="el-icon-close" @click="myclose" style="float: right"></i>
        </div>
      </template>
      <el-form
        :rules="rules"
        :model="ruleForm"
        ref="ruleForm"
        style="color: red; font-size: 30px"
      >
        <div>请输入耗材编码</div>
        <el-form-item prop="itemid">
          <el-input
            placeholder="请输入耗材编码"
            v-model="ruleForm.itemid"
            style="font-size: 30px"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnok" type="primary" class="close">确认</el-button>
        <el-button @click="myclose" type="danger" class="close">取消</el-button>
      </span>
    </el-dialog>
    <div class="shotmyphoto" v-show="showmyphoto">
      <img :src="shotmyphoto" alt="" />
    </div>
    <!-- 照相组件 -->
    <TakePhotos
      ref="TakePhotos"
      v-show="false"
      @update="receiveDataFromChild"
    ></TakePhotos>
  </div>
</template>

<script>
import { getgoodsInfo, getgoods, getphoid } from "../api/shop.js";
import TakePhotos from "./TakePhotos.vue";
import { mapState } from "vuex";
export default {
  name: "SetLemnt",
  components: {
    TakePhotos,
  },
  data() {
    return {
      isButtonDisabled: false,
      timer: null,
      showmyphoto: false,
      shotmyphoto: null,
      timeRemaining: 60, // 初始倒计时时间，单位：秒
      countdownInterval: null,
      loading: null,
      numform: [],
      rules: {
        itemid: [
          { trigger: "blur", required: true, message: "不能输入为空" },
          {
            pattern: /-?\d+/g,
            message: "请输入正确的耗材编码",
            trigger: "blur",
          },
        ],
      },
      dataimg: localStorage.getItem("outimg"),
      codeInput: "",
      inputvalue: "",
      // blur是否聚焦
      // disableBlur: false,
      ruleForm: { itemid: "" },
      // 弹层显示隐藏
      isshow: false,
      num: 1,
      add: [],
      // 页面 table的展示的数组
      shopdata: [],
      outshop: {
        shipmentOrderType: 11,
        shipmentOrderStatus: 11,
        details: [],
        receivableAmount: 1,
        photoBASE64Str: "",
        fileIdList: [],
      },
      list: [],
      strList: new Array(),
      qrcode: "",
      map: new Map(),
      wareHouseId: null,
    };
  },
  computed: {
    ...mapState(["warehouseId"]),
  },
  destroyed() {
    window.removeEventListener("keydown", this.handlekey);
  },
  mounted() {
    localStorage.setItem("outimg", "http://192.168.0.53:20001/haocai.jpg");
    const res = JSON.parse(localStorage.getItem("Warehouse"));
    const myfrom = localStorage.getItem("myfrom");
    if (myfrom.warehouseName === "值班室") {
      this.wareHouseId = res[0].id;
    } else {
      this.wareHouseId = localStorage.getItem("setmywarehouseId");
    }
    this.$refs.TakePhotos.openCamera();
    window.addEventListener("keydown", this.handlekey);
    this.startCountdown();
  },
  watch: {
    warehouseId(newvalue) {
      this.wareHouseId = this.$store.state.warehouseId;
    },
  },
  methods: {
    // 倒计时定时器
    startCountdown() {
      this.countdownInterval = setInterval(() => {
        if (this.timeRemaining > 0) {
          console.log(this.timeRemaining);
          this.timeRemaining--;
        } else {
          clearInterval(this.countdownInterval);
          this.$router.push("/Myecharts");
          console.log("倒计时结束");
        }
      }, 1000); // 1000 毫秒 = 1 秒
    },
    myclose() {
      this.ruleForm.itemid = "";
      this.isshow = !this.isshow;
    },
    handlekey(event) {
      clearInterval(this.countdownInterval); // 清除原来的定时器
      this.timeRemaining = 60; // 重置剩余时间
      this.startCountdown(); // 重新开始倒计时
      const regex = /\d/;
      if (regex.test(event.key) || event.key === "-" || event.key === "Enter") {
        if (event.key === "Enter") {
          console.log(event);
          this.inputvalue = this.strList.join("");

          if (this.inputvalue) {
            let start = this.inputvalue.lastIndexOf("-");
            if (start == -1) {
              this.$message.error("请输入正确的耗材编码");
              this.inputvalue = "";
              return;
            }
            let end = this.inputvalue.length;
            const thisvalue = this.inputvalue.substring(start + 1, end);
            getgoodsInfo({ itemId: thisvalue })
              .then((result) => {
                if (result.data.itemName) {
                  this.$message({
                    type: "success",
                    message: "添加耗材成功",
                    duration: 1000,
                  });
                  var v = this.map.get(thisvalue);

                  if (v == null) {
                    this.map.set(thisvalue, {
                      num: 1,
                      name: result.data.itemName,
                      value: result.data.id,
                    });
                  } else {
                    var count = v.num;
                    this.map.set(thisvalue, {
                      num: count + 1,
                      name: result.data.itemName,
                      value: result.data.id,
                    });
                  }

                  if (this.shopdata.length == 0) {
                    this.map.forEach((key) => {
                      this.shopdata.push({
                        name: key.name,
                        value: key.value,
                        num: key.num,
                      });
                    });
                  } else {
                    var cItem;
                    var e = this.map.get(thisvalue);

                    this.shopdata.forEach((item) => {
                      if (item.value == thisvalue) {
                        cItem = item;
                      }
                    });

                    console.log(cItem);
                    if (cItem == null) {
                      this.shopdata.push({
                        name: e.name,
                        value: e.value,
                        num: e.num,
                      });
                    } else {
                      cItem.name = e.name;
                      cItem.value = e.value;
                      cItem.num = e.num;
                    }
                  }
                  this.inputvalue = "";
                  this.strList = []; // 清空数组
                } else {
                  this.$message.error("耗材扫码错误请重试");
                  this.inputvalue = "";
                }
              })
              .catch(() => {
                this.$message.error("耗材扫码错误请重试");
                this.inputvalue = "";
              });
          }
        } else {
          this.strList.push(event.key);
        }
      }
    },
    // 返回上一级
    goblack() {
      this.$router.go(-1);
      this.shopdata = [];
    },
    // 删除物品
    del(item, data) {
      this.map.delete(item.value + "");
      this.shopdata.splice(data, 1);
    },
    // 拍照上传
    receiveDataFromChild(data) {
      // 发送请求
      // console.log();
      this.shotmyphoto = data;
      localStorage.setItem(
        localStorage.getItem("setmywarehouseId"),
        JSON.stringify(data)
      );
      getphoid({ BASE64Str: data, fileName: +new Date() }).then(async (res) => {
        this.outshop.fileIdList.push(res.data);
        if (this.shopdata.length) {
          this.loading = this.$loading({
            lock: true,
            text: "提交数据中，请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          this.isButtonDisabled = true;
          this.showmyphoto = true;
          this.outshop.details = this.shopdata.map((item) => {
            return {
              itemId: item.value,
              money: 0,
              warehouseId: this.wareHouseId,
              delFlag: 0,
              planQuantity: item.num,
              realQuantity: item.num,
            };
          });
          await getgoods(this.outshop);
          if (this.outshop.details.length) {
            this.$message({
              type: "success",
              message: "出库成功",
            });
            this.loading.close();
            this.ruleForm.itemid = "";
            this.timer = setInterval(() => {
              this.$router.push("/Myecharts");
            }, 2000);

            // this.outshop.details = [];
          } else {
            this.$message.error("出库失败");
            this.loading.close();
          }
        } else {
          this.$message.error("请添加出库耗材");
        }
      });
    },
    // 出库
    async Outbound() {
      this.$refs.TakePhotos.capturePhoto();
    },
    // 弹层确定
    btnok() {
      var flag = false;
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.isshow = false;
          var inputvalue = this.ruleForm.itemid;
          let start = inputvalue.lastIndexOf("-");
          if (start == -1) {
            this.$message.error("请输入正确的耗材编码");
            return;
          }
          var cItem;
          let end = inputvalue.length;
          const myid = inputvalue.substring(start + 1, end);
          const result = await getgoodsInfo({ itemId: myid });
          if (result.data.itemName) {
            this.$message({
              type: "success",
              message: "添加耗材成功",
            });
            this.shopdata.forEach((item, index) => {
              if (item.value == myid) {
                flag = true;
                cItem = item;
              }
            });

            if (flag) {
              cItem.num = cItem.num + 1;
              this.map.set(myid + "", {
                num: cItem.num,
                name: result.data.itemName,
                value: result.data.id,
              });
            } else {
              this.shopdata.push({
                name: result.data.itemName,
                num: 1,
                value: result.data.id,
              });
              this.map.set(myid + "", {
                num: 1,
                name: result.data.itemName,
                value: result.data.id,
              });
            }
            if (this.shopdata.length == 0) {
              this.shopdata.push({
                name: result.data.itemName,
                num: 1,
                value: result.data.id,
              });
              this.map.set(myid + "", 1);
            }

            console.log(this.map);
          } else {
            this.$message.error("编码错误请重试");
          }
        } else {
          this.$message.error("请输入正确的耗材编码");
        }
      });
    },
    // 手动输入id
    HandMovement() {
      this.isshow = !this.isshow;
      clearInterval(this.countdownInterval); // 清除原来的定时器
      this.timeRemaining = 60; // 重置剩余时间
      this.startCountdown(); // 重新开始倒计时
    },
    handChange(data) {
      this.codeInput = "";
      this.codeInput = data;
    },
  },
  beforeDestroy() {
    clearInterval(this.countdownInterval);
    clearInterval(this.timer);
  },
};
</script>

<style lang="scss" scoped>
::v-deep.el-form-item.el-form-item__label {
  font-size: 20px;
  color: red;
}
// 整个页面布局
.shop {
  display: flex;
  width: 100%;
  height: 98%;
  flex-direction: column;
  justify-content: center; /* 水平居中对齐 */
  align-items: center; /* 垂直居中对齐 */
  position: relative;
}
.shotmyphoto {
  position: fixed;
}
// 上边左右距离
.top {
  margin-top: 1rem;
  flex: 1;
  width: 100%;
  text-align: center;
}
// 上边左右距离
.topflex {
  display: flex;
  text-align: center;
  // justify-content: space-between;
}
// 中间距离上下
.middle {
  flex: 20;
}
.myrowshow {
  width: 1500px;
  height: 800px;
  overflow: auto;
  max-height: 800px;
}
// 中间内边距
.shopimg {
  width: 1400px;
  margin: 1%;
}
// 中间长宽
::v-deep .el-card__body {
  display: flex;
  justify-content: space-between;
  height: 5rem;
}
// 底部的样式
.bottom {
  flex: 1;
  width: 100%;
}
// button 按钮大小设置
.close {
  flex: 1;
  font-size: 2.8rem;
}
// 底部的样式
.buttomflex {
  text-align: center;
  display: flex;
}
// i标签鼠标悬停
i:hover {
  cursor: pointer;
}
.dds {
  position: relative;
}

.custom-title {
  font-size: 40px;
}
.el-input__inner {
  height: 60px;
}
</style>